﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cinchoo.Core.ETL;
using Cinchoo.Core;
using Cinchoo.Core.IO;
using System.IO;
using System.ComponentModel;

namespace Cinchoo.Core.ETL
{
    /// <summary>
    /// Task to monitor process. If 
    /// </summary>
    public class ChoETLFTPGetJob : ChoETLJob
    {
        #region Instance Properties

        [ChoETLTaskProperty]
        public string RequestUriString
        {
            get;
            set;
        }
        
        [ChoETLTaskProperty]
        public string DestinationFilePath
        {
            get;
            set;
        }

        [ChoETLTaskProperty]
        public string UserName
        {
            get;
            set;
        }

        [ChoETLTaskProperty]
        public string Password
        {
            get;
            set;
        }

        [ChoETLTaskProperty]
        public bool UseBinary
        {
            get;
            set;
        }

        [ChoETLTaskProperty]
        public bool UsePassive
        {
            get;
            set;
        }

        #endregion Instance Properties

        public ChoETLFTPGetJob(string requestUriString, string destinationFilePath = null)
        {
            ChoGuard.ArgumentNotNullOrEmpty(requestUriString, "RequestUriString");

            RequestUriString = requestUriString;
            DestinationFilePath = destinationFilePath;
            UseBinary = true;
            UsePassive = true;
        }

        protected override bool Initialize()
        {
            if (DestinationFilePath.IsNullOrWhiteSpace())
                DestinationFilePath = ChoPath.GetFullPath(new Uri(RequestUriString).AbsolutePath);

            return base.Initialize();
        }

        protected override void ExecuteTask()
        {
            //CREATE AN FTP REQUEST WITH THE DOMAIN AND CREDENTIALS
            System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(RequestUriString);
            if (!UserName.IsNullOrWhiteSpace())
                tmpReq.Credentials = new System.Net.NetworkCredential(UserName, Password);
            tmpReq.UseBinary = UseBinary;
            tmpReq.UsePassive = UsePassive;

            //GET THE FTP RESPONSE
            using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
            {
                using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
                {
                    using (Stream output = File.OpenWrite(DestinationFilePath))
                    {
                        ChoFileStream.CopyStream(tmpStream, output);
                    }
                }
            }
        }
    }
}
